﻿create procedure [mem].[kvAppend]
(
	@Key varchar(255) not null,
	@Version int not null,
	@NewVersion int out,
	@Values mem.kvValues readonly
) 
with NATIVE_COMPILATION, SCHEMABINDING, EXECUTE AS OWNER
as
begin atomic with (TRANSACTION ISOLATION LEVEL = SNAPSHOT, LANGUAGE = N'us_english')

	declare @KeyId bigint

	declare @OldVersion int
	update mem.kv 
		set 
			@KeyId = [KeyId],
			@OldVersion = [Version],
			[Version] = [Version] + 1
		where [Key] = @Key 

	if @@rowcount = 0
	begin
		set @NewVersion = -2147483648
		return;
	end

	if @Version != @OldVersion 
	begin
		declare @message nvarchar(350)
		set @message = 'Concurrency violation for key [' + @Key + ']. Reselect the value and try again.';
		throw 60001, @message, 1;
	end

	set @NewVersion = @OldVersion + 1
	insert mem.kvValues ([KeyId], Part) select @KeyId, [Part] from @Values 
end